<?php


namespace app\admin\controller;


use app\admin\model\TeacherModel;
use app\BaseController;
use app\Request;

class Teacher extends  BaseController
{
    public function getList(Request  $request)
    {
        $page = $request->post('page', 1);
        $limit = $request->post('limit', 10);
        $result = TeacherModel::order('id desc')->page($page, $limit)->select();
        $total = TeacherModel::count();

        $data = [
            'total' => $total,
            'current' => $page,
            'perpage' => $limit,
            'data' =>  $result
        ];

        return show(config('status.success'), '操作成功', $data);
    }


    /* 获取 */
    public function find()
    {
        if (!$this->request->auth) return show(config('status.auth'), 'Authorization Failed');
        $id = input('id', 0, 'intval');
        $data = TeacherModel::where(['id' => $id,])->field('id,name,phone')->find();
        if ($data) {
            return show(config('status.success'), 'success', $data);
        } else {
            return show(config('status.error_find'), '查询失败');
        }
    }

    /**
     * 创建
     * @param Request $request
     * @return \think\response\Json
     */
    public function create(Request $request)
    {
        $phone = $request->post('phone');
        $password = $request->post('password');
        if (strlen($phone) != 11) {
            return show(config('status.error'), '手机号格式下正确');
        }
        if (strlen($password) < 6) {
            return show(config('status.error'), '密码不得小于六位');
        }
        TeacherModel::create([
            'name' => $request->post('name'),
            'phone' => $request->post('phone'),
            'password' => sha1(md5($password))
        ]);
        return show(config('status.success'), '操作成功');
    }

    /**
     * 更新
     * @param Request $request
     * @return \think\response\Json
     */
    public function update(Request $request)
    {
        $phone = $request->post('phone');
        $password = $request->post('password');

        if (strlen($phone) != 11) {
            return show(config('status.error'), '手机号格式下正确');
        }

        $data = [
            'name' => $request->post('name'),
            'phone' => $phone,
        ];

        if (!empty($password)) {
            if (strlen($password) < 6) {
                return show(config('status.error'), '密码不得小于六位');
            }
            $data['password'] = sha1(md5($password));
        }

        TeacherModel::where(['id' => $request->post('id')])->update($data);
        return show(config('status.success'), '操作成功');
    }

    public function delete(Request  $request)
    {
        TeacherModel::destroy($request->post('id'));
        return show(config('status.success'), '操作成功');
    }
}